//ClinetBookServlet.java
package com.ylaihui.web;

import com.ylaihui.pojo.Book;
import com.ylaihui.pojo.Page;
import com.ylaihui.service.BookService;
import com.ylaihui.service.impl.BookServiceImpl;
import com.ylaihui.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ClinetBookServlet extends BaseServlet{

    BookService bookService = new BookServiceImpl();

    /**
     * 处理分页请求
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("page....");
        //1. 获取请求参数 pageNo 和 pageSize
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);

        //int pageNo = 1;
        //int pageSize = 4;
        //2. 调用 Service 层的page 方法 查询数据
        Page<Book> page = bookService.page(pageNo, pageSize);

        page.setUrl("client/bookServlet?action=page");

        //3. 将数据保存到 request域中
        req.setAttribute("page", page);

        //4. 请求转发
        req.getRequestDispatcher("/pages/client/index.jsp").forward(req, resp);
    }

    void pageByPrice(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //1. 获取请求参数 pageNo 和 pageSize
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        int min = WebUtils.parseInt(req.getParameter("min"), 0);
        int max = WebUtils.parseInt(req.getParameter("max"), Integer.MAX_VALUE);

        //2. 调用 Service 层的page 方法 查询数据
        Page<Book> page = bookService.pageByPrice(pageNo, pageSize, min, max);

        //page 的url 中携带价格区间，并让jsp页面回显
        StringBuilder stringBuilder = new StringBuilder("client/bookServlet?action=pageByPrice");
        if(req.getParameter("min") != null) {
            stringBuilder.append("&min=" + min);
        }
        if(req.getParameter("max") != null) {
            stringBuilder.append("&max=" + max);
        }
        page.setUrl(stringBuilder.toString());

        //3. 将数据保存到 request域中
        req.setAttribute("page", page);

        //4. 请求转发
        req.getRequestDispatcher("/pages/client/index.jsp").forward(req, resp);
    }

}
